// import Vue from 'vue'
// import Router from 'vue-router'
import MainRouter from '../modules/main/main-router'
const Login = resolve => require(['@/modules/login/Login'], resolve)
const Main = resolve => require(['@/modules/main/Main'], resolve)
const PageNotFound = resolve => require(['@/modules/page-not-found/PageNotFound'], resolve)
const MonitorCenterOld = resolve => require(['@/modules/monitor-center/MonitorCenter'], resolve)
const MonitorCenterNew = resolve => require(['@/modules/monitor-center/new/MonitorCenterNew'], resolve)
import store from '../store/index'
let Base64 = require('js-base64').Base64

// Vue.use(Router)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Main,
      children: [].concat.apply([{
        path: '',
        redirect: '/home'
      }], MainRouter.map(function (item) {
        return item.router
      }))
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    }, {
      path: '/monitor-center/all',
      name: 'monitor-center-all',
      component: MonitorCenterNew
    }, {
      path: '/monitor-center/site',
      name: 'monitor-center-site',
      component: MonitorCenterOld
    },
    {
      path: '*',
      component: PageNotFound
    }
  ]
})

/**
 * 验证当前用户是否有权限访问
 * */
function hasPermission(path) {
  const paths = getPaths()
  const bool = paths.some(item => {
    if (path.indexOf(item) > -1 || item.indexOf(path) > -1) {
      return true
    }
  })
  return bool
}

/**
 * 从sessionStorage中获取所有的paths
 * */
function getPaths() {
  const pathsSession = sessionStorage.getItem('paths')
  if (!pathsSession) {
    return []
  }
  const stringModule = Base64.decode(pathsSession)
  const paths = JSON.parse(stringModule)

  console.log('path ', paths)
  return paths
}


/*对前端页面*/
router.beforeEach((to, from, next) => {
  if (to.path === '/monitor-center/all') {
    sessionStorage.setItem('token', 'eyJhbGciOiJIUzI1NiJ9.eyJleHBpcmVUaW1lIjoxNTY1ODY0MDYzMjg4LCJpc3N1ZVRpbWUiOjE1NjU4NTMyNjMyODgsImlhdCI6MTU2NTg1MzI2MywianRpIjoiaWVtcDIwMTkwNDIwMTI0MTM1MDAwMDIxIn0.zM6iJQLmAXRNTQ7BmzALfPJSyq0l870338J1oLrwaLc')
    next()
    return
  }
  const token = sessionStorage.getItem('token')
  if (token) { // 判断用户是否登录
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (hasPermission(to.path)) { // 访问的路由有权限
        next()
      } else { // 无权限跳转到所有权限的默认第一个路由
        const paths = getPaths()
        next({ path: paths[0] })
      }
      // next()
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
